/**
* SoundLoader
* @author maze | guavestudios.com
* @version 0.1
*/

package ch.sfug.net.loader {
	import flash.events.Event;	import flash.events.ProgressEvent;	import flash.media.Sound;	import flash.net.URLRequest;	
	//{ EVENT DEFINITION
	/**
	* ProgressEvent.PROGRESS dispatched when loading a sound
	*/
	[Event(name = "ProgressEvent.PROGRESS", type = "flash.events.ProgressEvent")]
	/**
	* Event.OPEN dispatched when sound is opend
	*/
	[Event(name="Event.OPEN",type="flash.events.Event")]
	
	//}
	
	/**
	 * Loader for the Sound object
	 */
	public class SoundLoader extends AbstractLoader{
		
		//{ STATIC
		
		//}
		
		//{ MEMBERS
		private var sound:Sound; //internal sound
		private var connected:Boolean; //state of sound
		//}
		
		//{ GETTER-SETTER
		/**
		 * Returns the status of sound
		 * @returns true if connected else false
		 */
		public function get Connected():Boolean {
			return this.connected;
		}
		/**
		 * Get the duration
		 * @return duration
		 */
		public function get duration():Number
		{
			return int(sound.length/(sound.bytesLoaded/sound.bytesTotal));
		}
		//}
		
		
		
		//{ INIT
		public function SoundLoader(url:URLRequest=null) {
			super(url);
			init();
		}
		private function init():void {
			
		}
		//}
		
		//{ PUBLIC METHODS
		/**
		 * @inheritDoc
		 */
		public function getResult():Sound {
			return sound;
		}
		//}
		
		//{ OVERRIDEN METHODS
		/**
		 * @inheritDoc
		 */
		public override function load(req:URLRequest=null):void
		{
			if (req)
			{
				request = req;
			}
			
			//if there is one running, close it
			if (sound) if (sound.isBuffering) sound.close();
			
			//create a new sound to avoid Error: 2037 <-- anyone knows why this error happens?
			sound = new Sound();
			sound.addEventListener(ProgressEvent.PROGRESS, sound_progress);
			sound.addEventListener(Event.OPEN, sound_open);
			sound.load(request);
			
			//set connected to true
			connected = true;
			
			//onLoadStarts(); //currently deactivated.... not in code
		}
		/**
		 * Stops the loading of a sound
		 */
		public override function stop(  ):void {
				sound.close();
				connected = false;
		}
		//}
		
		//{ PRIVATE METHODS
		
		//}
		
		//{ EVENT HANDLING
		private function sound_progress(e:ProgressEvent):void
		{
			dispatchEvent(e);
		}
		private function sound_open(e:Event):void
		{
			dispatchEvent(e);
		}
		//}
		
	}
	
}
